package cn.ncist.health_backend.controller;

import cn.ncist.common.RespResult;
import cn.ncist.constant.MessageConstant;
import cn.ncist.health_interface.service.OrderSettingService;
import cn.ncist.pojo.OrderSetting;
import cn.ncist.utils.POIUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @DubboReference
    private OrderSettingService orderSettingService;

    @PostMapping("/upload")
    public RespResult upload(@RequestParam("excelFile") MultipartFile excelFile) {
        if (excelFile == null) {
            throw new RuntimeException("传入的参数为空");
        }
        try {
            List<String[]> excelRows = POIUtils.readExcel(excelFile);
            if (excelRows != null && excelRows.size() > 0) {
                List<OrderSetting> orderSettingList = new ArrayList<>();
                for (String[] strings : excelRows) {
                    OrderSetting orderSetting
                            = new OrderSetting(null, new Date(strings[0]), Integer.parseInt(strings[1]), null);
                    orderSettingList.add(orderSetting);
                }
                orderSettingService.add(orderSettingList);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new RespResult(true, MessageConstant.IMPORT_ORDERSETTING_FAIL);

        }
        return new RespResult(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }

    @GetMapping("/getOrderSettingByMonth")
    public RespResult getOrderSettingByMonth(String date) {//参数格式为：2022-8
//        log.info(date);
        try {
            List<Map<String,Object>> orderSettingMap = orderSettingService.getOrderSettingByMonth(date);
            return new RespResult(true, MessageConstant.GET_ORDERSETTING_SUCCESS, orderSettingMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new RespResult(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    @PostMapping("/editNumberByDate")
    public RespResult edit(@RequestBody OrderSetting orderSetting){
        try {
            orderSettingService.updateByMonth(orderSetting);
            return new RespResult(true,"根据日期修改可预约人数成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new RespResult(true,"根据日期修改可预约人数失败");
        }
    }
}
